package com.alinesno.cloud.base.logger.agent.aop;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alinesno.cloud.base.logger.agent.tool.IPUtils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 用户登陆及页面操作监控 , AOP切面 ：多个切面时，@Order(i)注解来标识切面的优先级。i的值越小，优先级越高,看方法运行的时间 
 * @author LuoAnDong
 * @since 2019年4月8日 下午8:30:43
 */
@Order(5)
@Aspect
@Component
public class CurrentAccountMonitorAspect {
	
    private static final Logger log = LoggerFactory.getLogger(CurrentAccountMonitorAspect.class);
    
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")  
    public void pointcut(){
    }
 
    //统计请求的处理时间
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) {
        Object result = null;
        long beginTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = point.proceed();
        } catch (Throwable e) {
        	e.printStackTrace();
        }
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        
        // 保存日志
        monitorAccountOperator(point, time);
        
        return result;
    }

    /**
     * 记录用户操作日志
     * @param joinPoint
     * @param time
     */
	private void monitorAccountOperator(ProceedingJoinPoint joinPoint, long time) {
		AccountMonitorBean bean = new AccountMonitorBean() ; 
		
		bean.setTime(time);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String className = joinPoint.getTarget().getClass().getName(); // 请求的方法名
        String methodName = signature.getName();
        bean.setMethod(className+":"+methodName);
        
        // 请求的方法参数值 请求的方法参数名称
        Object[] args = joinPoint.getArgs();
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        
        String[] paramNames = u.getParameterNames(method);
        if (args != null && paramNames != null) {
            String params = "";
            for (int i = 0; i < args.length; i++) {
                params += "  " + paramNames[i] + ": " + args[i];
            }
            bean.setParams(params);
        }
        
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes() ; 
        HttpServletRequest request = attributes.getRequest(); 
        String agent = request.getHeader("User-Agent");
        String url = request.getRequestURL().toString() ; 
      
        bean.setUrl(url);
        bean.setAgent(agent);
        bean.setIp(IPUtils.getIpAddr(request)); // 设置IP地址
        
        // 设置用户
        Object account = request.getSession().getAttribute("CURRENT_USER") ; 
        if(account != null) {
        	JSONObject json = JSONUtil.parseObj(account) ; 
        	log.debug("current user = {}" , json.toString());
        	
        	bean.setAccountId(json.getStr("id"));
        	bean.setAccountName(json.getStr("name"));
        	bean.setApplicationId(json.getStr("applicationId"));
        	bean.setLoginName(json.getStr("loginName")) ; 
        }
        
        bean.setCreateTime(new Date());
        log.debug("当前用户操作:[{}]" , JSONUtil.toJsonStr(bean));
    }
 
}


